package com.lsec.springbootinit.service.impl;


import cn.hutool.core.collection.ListUtil;
import com.lsec.springbootinit.mapper.UserMapper;
import com.lsec.springbootinit.model.common.LoginUser;
import com.lsec.springbootinit.model.entity.SysUser;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static com.lsec.springbootinit.model.common.ServiceException.exception;

/**
 * 用户详细信息实现类
 *
 * @author Cherry
 * @date 2023/06/12
 */
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        SysUser sysUser = userMapper.selectOne(SysUser::getUsername, username);
        //如果查询不到数据就通过抛出异常来给出提示
        if(Objects.isNull(sysUser)){
            throw new UsernameNotFoundException("用户名或密码错误!");
        }
        //TODO 根据用户查询权限信息 添加到LoginUser中
        List<String> list = new ArrayList<>(List.of("test"));

        //封装成UserDetails对象返回 
        return new LoginUser(sysUser, list);
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("test"));
        LoginUser loginUser = new LoginUser(new SysUser(), list);
        System.out.println("new BCryptPasswordEncoder().encode(\"admin\") = " + new BCryptPasswordEncoder().encode("admin"));
    }
}